<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\analysis\data\info;

use app\model\mongo\MongoInfoModel;
use app\model\mongo\MongoOePicModel;
use app\model\mongo\MongoOeVideoModel;
use app\model\OeProjectPromotionModel;
use app\service\BaseService;
use think\model\Collection;

class OceanUseMaterialService extends BaseService
{
    public function __construct()
    {
    }

    /**
     * 脚本执行.
     */
    public function runTask(OeProjectPromotionModel $model): bool
    {
        if (! $model->getKey()) {
            return self::setError('未知广告模型');
        }
        $promotionMaterials = Collection::make($model->getAttr('promotion_materials'))->toArray();
        if (! empty($promotionMaterials['video_material_list'])) {
            $this->setVideoUse($model->getAttr('account_id'), $promotionMaterials['video_material_list']);
        }
        if (! empty($promotionMaterials['image_material_list'])) {
            $this->setPicUse($model->getAttr('account_id'), $promotionMaterials['image_material_list']);
        }
        return true;
    }

    /**
     * 设置视频已使用.
     * @param int $accountId 账户id
     * @param array $items 视频列表
     */
    private function setVideoUse(int $accountId, array $items): bool
    {
        if (! $items) {
            return true;
        }
        foreach ($items as $item) {
            MongoOeVideoModel::update([
                'is_use' => MongoInfoModel::IS_USE,
            ], [
                'material_id' => strval($item['material_id']),
                'account_id' => $accountId,
            ]);
        }
        return true;
    }

    /**
     * 设置图片已使用.
     * @param int $accountId 账户id
     * @param array $items 视频列表
     */
    private function setPicUse(int $accountId, array $items): bool
    {
        if (! $items) {
            return true;
        }
        foreach ($items as $item) {
            foreach ($item['images'] as $v) {
                MongoOePicModel::update([
                    'is_use' => MongoInfoModel::IS_USE,
                ], [
                    'material_id' => strval($v['material_id']),
                    'account_id' => $accountId,
                ]);
            }
        }
        return true;
    }
}
